package agu.json;

import org.json.JSONObject;
import org.json.JSONTokener;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@SuppressWarnings({"unchecked", "NullableProblems"})
public class JSONObject2 extends JSONObject implements $JSON<String>
{
    /** nameValuePairs */
    final Map<String, Object> content;

    public JSONObject2(){
        super();
        content = JSONUtil.getField(this, JSONObject.class, HashMap.class);
    }

    public JSONObject2(Object input){
        this();
        if(input instanceof CharSequence){
            input = new JSONTokener(input.toString());
        }
        if(input instanceof JSONTokener){
            try{
                Object next = ((JSONTokener)input).nextValue();
                input = (JSONObject)next;
            }catch(Exception ex){
                ex.printStackTrace();
                return;
            }
        }
        content.putAll(JSONUtil.toMap(input));
    }

    public JSONObject2 forEach(JSONUtil.EachCallback<JSONObject2, String> callback){
        JSONUtil.forEach(this, callback);
        return this;
    }

    /** 除去{@link JSONObject#NULL} */
    public JSONObject2 trim(){
        for(Iterator<String> it = keys(); it.hasNext(); ){
            String key = it.next();
            if(isNull(key)){
                it.remove();
            }
        }
        return this;
    }

    @Override
    public String toString(int indentSpaces){
        try{
            return super.toString(indentSpaces);
        }catch(Exception e){
            return "";
        }
    }

    @Override
    public Object opt(String name){
        return super.opt(name);
    }

    @Override
    public JSONObject2 put(String name, boolean value){
        put(name, (Object)value);
        return this;
    }

    @Override
    public JSONObject2 put(String name, double value){
        put(name, (Object)value);
        return this;
    }

    @Override
    public JSONObject2 put(String name, int value){
        put(name, (Object)value);
        return this;
    }

    @Override
    public JSONObject2 put(String name, long value){
        put(name, (Object)value);
        return this;
    }

    @Override
    public JSONObject2 put(String name, Object value){
        try{
            super.put(name, value);
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return this;
    }

    @Override
    public JSONObject2 putOpt(String name, Object value){
        if(name != null && value != null){
            put(name, value);
        }
        return this;
    }
}
